package com.springboot.base.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.base.constant.AuthorityConstants;
import com.springboot.base.entity.User;
import com.springboot.base.util.IPUtil;
import com.springboot.base.util.JWTUtil;
import com.springboot.base.util.RedisUtil;
import com.springboot.base.util.SentaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *<p>
 *
 *  在请求之前的拦截器
 *</p>
 * @author 福小林
 **/
@Configuration
public class EncodingInterceptor  implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private ObjectMapper mapper;

    private Logger logger = LoggerFactory.getLogger(EncodingInterceptor.class);
    /**
     * 在业务处理器处理请求之前被调用。
     * 预处理，可以进行编码、安全控制、权限校验等处理
     * @param request 请求参数
     * @param response 响应参数
     * @param handler 数据对象
     * @return 是否通过拦截器
     * @throws Exception 有可能的一次
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*if(handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod)handler;
            String[] value = h.getMethodAnnotation(RequiresPermissions.class).value();
            System.out.println("用户想执行的操作是:"+value[0]);
            //判断后执行操作...
        }*/

        return true;
    }


    public User getUser(String username) throws Exception {
        // 通过用户名查询用户信息
        String userString =redisUtil.get(AuthorityConstants.USER_CACHE_PREFIX + username);

        if (StringUtils.isBlank(userString)){
            throw new Exception();
        }
        else{
            return mapper.readValue(userString, User.class);
        }

    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("afterCompletion...");
    }

}
